using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using PowerManage.API.Auth;
using PowerManage.Entity;
using PowerManage.Entity.Dtos.Accounts;
using PowerManage.Service;

namespace PowerManage.API.Controllers;

/// <summary>
/// 账号
/// </summary>
[Route("api/[controller]")]
[PermissionAuthorize]
public class AccountsController : BaseController
{
    private readonly IRolePermissionService _rolePermissionRepository;

    //http上下文 获取当前用户登录信息 webapi默认注入，直接使用就行
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly UserManager<EleUser> _userManager;
    private readonly SignInManager<EleUser> _signInManager;

    public AccountsController(IRolePermissionService rolePermissionRepository,
        IHttpContextAccessor httpContextAccessor, UserManager<EleUser> userManager,
        SignInManager<EleUser> signInManager)
    {
        _rolePermissionRepository = rolePermissionRepository;
        _httpContextAccessor = httpContextAccessor;
        _userManager = userManager;
        _signInManager = signInManager;
    }

    /// <summary>
    /// 获取个人信息
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Authorize]
    public async Task<IActionResult> Get()
    {
        // 获取个人信息
        var userName = _httpContextAccessor.HttpContext.User.Identity.Name;
        var user = await _userManager.FindByNameAsync(userName);
        var roleList = await _userManager.GetRolesAsync(user);
        var accountDto = new AccountDto
        {
            Roles = roleList.ToArray(),
            Avatar = "",
            Name = userName,
            Introduction = string.IsNullOrEmpty(user.FullName) ? userName : user.FullName
        };

        return Ok(accountDto);
    }

    /// <summary>
    /// 获取授权列表
    /// </summary>
    /// <returns></returns>
    [HttpGet("permissions")]
    public async Task<IActionResult> GetPermissions()
    {
        //获取登录的用户名
        var userName = _httpContextAccessor.HttpContext.User.Identity.Name;
        var user = await _userManager.FindByNameAsync(userName);
        var roleList = await _userManager.GetRolesAsync(user);
        var rolePermissions = new Dictionary<long, AccountPermissionsDto>();
        foreach (var roleName in roleList)
        {
            //获取角色权限列表
            var accountPermissionsDtoList = await _rolePermissionRepository.GetRolePermissions(roleName);
            //去掉重复的权限
            foreach (var accountPermissionsDto in accountPermissionsDtoList)
            {
                if (!rolePermissions.ContainsKey(accountPermissionsDto.Id))
                {
                    rolePermissions.Add(accountPermissionsDto.Id, accountPermissionsDto);
                }
            }
        }

        //返回权限列表
        var list = rolePermissions.Values.ToList();
        return Ok(list);
    }

    /// <summary>
    /// 修改密码
    /// </summary>
    /// <param name="accountUpdatePasswordDto"></param>
    /// <returns></returns>
    /// PATCH： 部分更新资源部分字段
    [HttpPatch("password")]
    public async Task<IActionResult> UpdatePassword([FromBody] AccountUpdatePasswordDto accountUpdatePasswordDto)
    {
        // 修改密码
        var userName = _httpContextAccessor.HttpContext.User.Identity.Name;
        var result =
            await _signInManager.PasswordSignInAsync(userName, accountUpdatePasswordDto.OldPassword, false, false);
        if (result.Succeeded)
        {
            var user = await _userManager.FindByNameAsync(userName);
            var passwordHasher = new PasswordHasher<EleUser>();
            user.PasswordHash = passwordHasher.HashPassword(user, accountUpdatePasswordDto.NewPassword);
            await _userManager.UpdateAsync(user);
            return Ok();
        }
        else
        {
            return BadRequest(new ResponseResultDto().SetError("修改密码失败"));
        }
    }
}